﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Newtonsoft.Json.Linq;
using Sparklings.JsonUtils;
using System;
using System.Linq;

namespace Sparklings.LevelElements
{
    public class StarTile : EmptyTile
    {
        public StarTile(Level l, int x, int y)
            : base(l, x, y)
        {
            Collected = false;
            TimeSinceFlashStart = 0;
        }
        public override void LoadGraphicsRelatedElements()
        {
            base.LoadGraphicsRelatedElements();
            TextureTaken = Level.ContentManager.Load<Texture2D>("star_taken");
            TextureNormal = Level.ContentManager.Load<Texture2D>("star_normal");
        }
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
            if (GetCurrentlyContainedSparklings().Count() != 0)
            {
                Collected = true;
            }
            TimeSinceFlashStart += gameTime.ElapsedGameTime.TotalSeconds;
        }
        public override void DrawBase(Rendering.RenderContext rc)
        {
            base.DrawBase(rc);
            if (Collected)
            {
                rc.Draw(TextureTaken, Center);
            }
            else
            {
                rc.Draw(TextureNormal, Center);
            }
        }
        public override void DrawEmissive(Rendering.RenderContext rc)
        {
            base.DrawEmissive(rc);
            if (!Collected)
            {
                ;
                rc.Draw(TextureNormal, Center,Color.FromNonPremultiplied(new Vector4((float)(Math.Abs(Math.Sin(TimeSinceFlashStart)*0.5)+0.5))));
            }
        }
        public override JToken GetJsonData(JsonOverrider converter)
        {
            var ret = new JObject();
            ret["collected"] = Collected;
            return ret;
        }
        public new static object ConstructFromData(JsonOverrider converter, JToken toConvert, Level level, int x, int y)
        {
            return new StarTile(level, x, y) { Collected = converter.Read<bool>(toConvert["collected"]) };
        }
        public bool Collected
        {
            get { return collected; }
            set
            {
                collected = value;
                BaseTexture = collected ? TextureTaken : TextureNormal;
            }
        }
        private bool collected = false;
        private Texture2D TextureTaken;
        private Texture2D TextureNormal;
        private double TimeSinceFlashStart;
    }
}
